package com.lishe.lishe.lishe.module.commonclass;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lishe.base.common.config.Constants;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.base.BaseBean;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.excitation.activity.MineWelfareActivity;
import com.lishe.lishe.lishe.module.main.activity.MainActivity0;
import com.lishe.lishe.lishe.module.mall.activity.GoodsDetailActivity;
import com.lishe.lishe.lishe.module.mall.http.HttpMall;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.LogUtil;
import com.lishe.lishe.lishe.utils.ToastUtil;
import com.lishe.lishe.retrofit.DataResponseListener;

import java.util.ArrayList;
import java.util.Stack;

import wendu.webviewjavascriptbridge.WVJBWebView;

/**
 * Created by shino on 2017/10/18.
 * 网页专用activity
 */

public class WebActivity extends BaseActivity implements View.OnClickListener {

    private TextView title;
    private WVJBWebView myWebView = null;
    private String url;
    public final static int FILECHOOSER_RESULTCODE = 1001;
    public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 1002;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    WebSettings webSettings;
    private JSMethod jsMethod;
    private boolean isGetOut = false;//是否直接退出webview
    private boolean isGetOutToMain = false;//是否直接退出webview，跳到指定页
    private boolean isGetOutToWealfareList = false;//是否直接退出webview，跳到指定页
    private ProgressBar mProgressBar;

    private ArrayList<String> loadHistoryUrls = new ArrayList<String>();
    private MyWebViewClient webViewClient;

    public static void jump(Activity activity, String url) {
        Intent intent = new Intent(activity, WebActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("isGetOutToMain", false);
        activity.startActivity(intent);
    }

    public static void jump(Activity activity, String url, String title) {
        Intent intent = new Intent(activity, WebActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        intent.putExtra("isGetOutToMain", false);
        activity.startActivity(intent);
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_webview);
        url = getIntent().getStringExtra("url");
        title = findViewById(R.id.title_text_title);
        isGetOutToMain = getIntent().getBooleanExtra("isGetOutToMain", false);
        if (getIntent().getStringExtra("title") != null) {
            title.setText(getIntent().getStringExtra("title"));
        } else {
            if (url == null) {//从短信进来
                isGetOutToWealfareList = true;
                url = getIntent().getDataString().replace("lishe168://", "") + "&token=" + Globals.getToken() + "&source=Android";
                title.setText("福利领取");
                title.setVisibility(View.VISIBLE);
                if (TextUtils.isEmpty(Globals.getToken())) {//去登录
                    doCheckLoginIfNeedAndRedirectAuth(WebActivity.this);
                }
            } else {
                if (url.contains("?SN=") || url.contains("/z/")) {//去登录
                    isGetOutToWealfareList = true;
                    title.setText("福利领取");
                    title.setVisibility(View.VISIBLE);
                    url = url + "&token=" + Globals.getToken() + "&source=Android";
                    if (TextUtils.isEmpty(Globals.getToken())) {
                        doCheckLoginIfNeedAndRedirectAuth(WebActivity.this);
                    }
                }
            }
        }
        loadHistoryUrls.add(url);
        initView();
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void initView() {
        myWebView = findViewById(R.id.webView);
        mProgressBar = findViewById(R.id.progressBar);
        findViewById(R.id.title_left_button).setOnClickListener(this);
        webSettings = myWebView.getSettings();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webSettings.setLoadsImagesAutomatically(true);
        } else {
            webSettings.setLoadsImagesAutomatically(false);
        }

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

        //支持插件
        webSettings.setPluginState(WebSettings.PluginState.ON);


        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        myWebView.clearCache(true);
        //设置自适应屏幕，两者合用
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //适配屏幕
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(true); //隐藏原生的缩放控件
        webSettings.setDefaultFontSize(15);//默认字体大小
        //支持自动播放音乐
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            webSettings.setMediaPlaybackRequiresUserGesture(false);
        }
        myWebView.setWebChromeClient(new MyWebChromeClient());

        JsBean bean = new JsBean();
        bean.setAppToken(Globals.getToken());
        bean.setGetCouponUrl(Globals.LISHE_URL + "Coupon/getCoupon");
        //ToastUtil.showToast(WebActivity.this, new Gson().toJson(bean).toString());
        //String value = "getCouponUrl&=" + Globals.LISHE_URL + "Coupon/getCoupon";
        myWebView.callHandler(Constants.INIT_JS_FUNCTION, new Gson().toJson(bean), (WVJBWebView.WVJBResponseCallback<String>) data -> LogUtil.d("申请js交互成功"));
        myWebView.registerHandler(Constants.JS_TO_GOODS_METHOD, (WVJBWebView.WVJBHandler<String, String>)
                (data, wvjbResponseCallback) -> GoodsDetailActivity.jump(WebActivity.this, data));
        myWebView.registerHandler(Constants.JS_CallOCWithGetCoupon, new WVJBWebView.WVJBHandler<Object, Object>() {
            @Override
            public void handler(Object o, WVJBWebView.WVJBResponseCallback<Object> wvjbResponseCallback) {
                int couponId = (Integer) o;
                getCoupon(couponId + "");
            }
        });
        webViewClient = new MyWebViewClient();
        myWebView.setWebViewClient(webViewClient);
        myWebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
//                if (event.getAction() == KeyEvent.ACTION_DOWN) {
//                    if (keyCode == KeyEvent.KEYCODE_BACK && myWebView.canGoBack()) {  //表示按返回键
//                        myWebView.goBack();   //后退
//                        return true;    //已处理
//                    }
//                }
                return pageGoBack(myWebView,webViewClient);
            }
        });
        myWebView.loadUrl(url);

//        jsMethod = new JSMethod();
//        myWebView.addJavascriptInterface(jsMethod, "doApp");
    }

    /**
     * 领取优惠券
     */
    private void getCoupon(String couponId) {
        HttpMall.getCoupon(couponId, Globals.getToken(), new DataResponseListener<BaseBean>() {
            @Override
            public void onSuccess(BaseBean bean) {
                ToastUtil.showToast(WebActivity.this, bean.getMsg());
            }

            @Override
            public void onFail(String failMessage) {
                ToastUtil.showToast(WebActivity.this, failMessage);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(WebActivity.this, R.string.network_or_server_exception);
            }
        });
    }

    public boolean pageGoBack(WebView web, MyWebViewClient client) {
        final String url = client.popLastPageUrl();
        if (url != null) {
            web.loadUrl(url);
            return true;
        }
        finish();
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_button:
                if (isGetOutToMain) {
                    finish();
                    Intent intent = new Intent(WebActivity.this, MainActivity0.class);
                    startActivity(intent);
                } else if (isGetOutToWealfareList) {
                    finish();
                    MineWelfareActivity.jump(WebActivity.this);
                } else {
                    if (isGetOut) {
                        finish();
                    } else {
//                        if (myWebView.canGoBack()) {
//                            myWebView.goBack();
//                        } else {
//                            super.onBackPressed();
//                        }
                        pageGoBack(myWebView,webViewClient);
                    }
                }
                break;
        }
    }

    private class MyWebViewClient extends WebViewClient {
        /**
         * 记录URL的栈
         */
        private final Stack<String> mUrls = new Stack<>();
        /**
         * 判断页面是否加载完成
         */
        private boolean mIsLoading;
        private String mUrlBeforeRedirect;

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (mIsLoading && mUrls.size() > 0) {
                mUrlBeforeRedirect = mUrls.pop();
            }
            recordUrl(url);
            this.mIsLoading = true;
        }

        /**
         * 记录非重定向链接, 避免刷新页面造成的重复入栈
         *
         * @param url 链接
         */
        private void recordUrl(String url) {
            //这里还可以根据自身业务来屏蔽一些链接被放入URL栈
            if (!TextUtils.isEmpty(url) && !url.equalsIgnoreCase(getLastPageUrl())) {
                mUrls.push(url);
            } else if (!TextUtils.isEmpty(mUrlBeforeRedirect)) {
                mUrls.push(mUrlBeforeRedirect);
                mUrlBeforeRedirect = null;
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {//url拦截事件
//            view.loadUrl(url);
//            title.setText(view.getTitle());
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (this.mIsLoading) {
                this.mIsLoading = false;
            }
            imgReset();
        }

        /**
         * 获取上一页的链接
         **/
        private synchronized String getLastPageUrl() {
            return mUrls.size() > 0 ? mUrls.peek() : null;
        }

        /**
         * 推出上一页链接
         */
        public String popLastPageUrl() {
            if (mUrls.size() >= 2) {
                mUrls.pop(); //当前url
                return mUrls.pop();
            }
            return null;
        }

    }

    @Override
    public void onPause() {
        myWebView.onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        myWebView.onResume();
        super.onResume();

    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
//        myWebView.setVisibility(View.GONE);
    }

    @Override
    public void finish() {
        ViewGroup view = (ViewGroup) getWindow().getDecorView();
        view.removeAllViews();
        super.finish();
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        myWebView.destroy();
        super.onDestroy();
    }

    private class MyWebChromeClient<FileChooserParams> extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {

            if (newProgress == 100) {
                mProgressBar.setVisibility(View.GONE);//加载完网页进度条消失
            } else {
                mProgressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                mProgressBar.setProgress(newProgress);//设置进度值
            }
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooserImpl(uploadMsg);
        }

        // For Android 3.0+ 文件选择
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            openFileChooserImpl(uploadMsg);
        }

        // For Android > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType, String capture) {
            openFileChooserImpl(uploadMsg);
        }

        // For Android > 4.4 为了支持安卓5.0和6.0等高版本系统
        public boolean onShowFileChooser(WebView webView,
                                         ValueCallback<Uri[]> filePathCallback,
                                         FileChooserParams fileChooserParams) {
            openFileChooserImplForAndroid5(filePathCallback);
            return true;
        }
    }

    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"),
                FILECHOOSER_RESULTCODE);
    }

    private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
        mUploadCallbackAboveL = uploadMsg;
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
        startActivityForResult(chooserIntent,
                FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
    }


    @Override
    public void onBackPressed() {
        if (isGetOutToMain) {
            finish();
            Intent intent = new Intent(WebActivity.this, MainActivity0.class);
            startActivity(intent);
        } else if (isGetOutToWealfareList) {
            finish();
            MineWelfareActivity.jump(WebActivity.this);
        } else {
            if (isGetOut) {
                finish();
            } else {
                if (myWebView.canGoBack()) {
                    myWebView.goBack();
                } else {
                    super.onBackPressed();
                }
            }
        }
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK && myWebView.canGoBack()) {
//            myWebView.goBack();// 返回前一个页面
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri result = (data == null || resultCode != RESULT_OK) ? null : data
                .getData();
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;

        } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
            if (null == mUploadCallbackAboveL)
                return;
            if (result != null) {
                mUploadCallbackAboveL.onReceiveValue(new Uri[]{result});
            } else {
                mUploadCallbackAboveL.onReceiveValue(new Uri[]{});
            }
            mUploadCallbackAboveL = null;
            // onActivityResultAboveL(requestCode, resultCode, data);
        }
    }

    /**
     * H5点击监听
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void listenerJsOnclik() {
        myWebView.evaluateJavascript("value()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
                Log.e("点击监听", "onReceiveValue value=" + s);
            }
        });
    }

    class JSMethod {
        /**
         * 前端使用的android函数
         *
         * @param type 0、默认，1、商品详情，2、加入购物车，3、积分领取,4、可以结束（jsonString=false不是立即结束，true为立即结束）
         */
        @JavascriptInterface
        public void doApp(int type, String jsonString) {
//            if(jsonString==null){
//                jsonString="没有值";
//            }
//            Log.e("Webview_doApp()",type+"--"+jsonString);
//            toast("H5调用app-type="+type+"str-"+jsonString);
            switch (type) {
                case 0:
                    normnalMethod(jsonString);
                    break;
                case 1:
                    getGoodsMethod(jsonString);
                    break;
                case 2:
                    addToGoodsCarMethod(jsonString);
                    break;
                case 3:
                    getIntegralMethod(jsonString);
                    break;
                case 4:
                    finishWeb(jsonString);
                    break;
            }
        }

        /**
         * 默认方法
         *
         * @param jsonString
         */
        public void normnalMethod(String jsonString) {
            Log.e("normnalMethodH5交互", jsonString);
        }

        /**
         * 商品详情
         *
         * @param jsonString
         */
        public void getGoodsMethod(String jsonString) {
            Log.e("getGoodsMethodH5交互", jsonString);
            GoodsDetailActivity.jump(WebActivity.this, jsonString);
        }

        /**
         * 添加到购物车
         *
         * @param jsonString
         */
        public void addToGoodsCarMethod(String jsonString) {
            Log.e("addToGoodsCarMethodH5交互", jsonString);
        }

        /**
         * 积分领取
         *
         * @param jsonString
         */
        public void getIntegralMethod(String jsonString) {
            finish();
            Intent intent = new Intent(WebActivity.this, MainActivity0.class);
            startActivity(intent);
        }

        /**
         * 可结束操作
         *
         * @param jsonString
         */
        public void finishWeb(String jsonString) {
            Log.e("web结束这个页面", jsonString);
            if (jsonString.equals("false")) {
                isGetOut = true;
            } else if (jsonString.trim().equals("true")) {
                Log.e("关闭", "finish");

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                        if (isGetOutToMain) {
                            MainActivity0.jump(WebActivity.this);
                        }
                        if (isGetOutToWealfareList) {
                            MineWelfareActivity.jump(WebActivity.this);
                        }
                    }
                });

            }
        }
    }

    /**
     * 对图片进行重置大小，宽度就是手机屏幕宽度，高度根据宽度比便自动缩放
     * http://blog.csdn.net/smileiam/article/details/72123227,资料来源
     **/
    private void imgReset() {
        myWebView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName('img'); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "var img = objs[i];   " +
                "    img.style.maxWidth = '100%'; img.style.height = 'auto';  " +
                "}" +
                "})()");
    }
}
